package top.arryweb.application.domain.pojo;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import top.arryweb.application.common.exception.BusinessRuntimeException;
import top.arryweb.application.domain.dto.CreateTradeBlotterDTO;

/**
 * <p>
 * 交易流水表
 * </p>
 *
 * @author astupidcoder
 * @since 2021-05-27
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@NoArgsConstructor
public class BookKeepTradeBlotter implements Serializable {

  private static final long serialVersionUID = 1L;

  @TableId(value = "id", type = IdType.ID_WORKER)
  private Long id;

  private Long createBy;

  @TableField(fill = FieldFill.INSERT)
  @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  private LocalDateTime createTime;

  private Boolean deleteFlag = false;

  private Boolean enableFlag = true;

  @TableField(fill = FieldFill.UPDATE)
  @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  private LocalDateTime updateTime;

  private Long version;

  private BigDecimal amount;

  /**
   * 分账订单id，如果没有则默认为0
   */
  private Long distributionOrderId;

  /**
   * 订单id
   */
  public Long orderId;

  /**
   * 交易类型(支付，退款)
   */
  private Integer payType;

  /**
   * 交易时间
   */
  @TableField(fill = FieldFill.INSERT)
  @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  private LocalDateTime tradeTime;

  /**
   * 用户id
   */
  private Long userId;

  /**
   * 商户id，若平台为单商户，可不填写商户id，默认为0
   */
  private Long merchantId;

  /**
   * 数据校验--创建交易流水
   */
  public BookKeepTradeBlotter(CreateTradeBlotterDTO dto) {
    this.createTime = LocalDateTime.now();
    if (dto.getAmount().compareTo(BigDecimal.valueOf(0)) < 0) {
      throw new BusinessRuntimeException("当前资金不应该小于0");
    }
    this.amount = dto.getAmount();
    this.distributionOrderId = dto.getDistributionOrderId();
    this.orderId = dto.getOrderId();
    this.payType = dto.getPayType();
    this.userId = dto.getUserId();
    this.merchantId = dto.getMerchantId();
  }

  public BookKeepTradeBlotter setTradeTime(LocalDateTime tradeTime, LocalDateTime createTime) {
      if (tradeTime.isBefore(createTime)) {
          throw new BusinessRuntimeException("交易时间不应该在订单创建时间之前");
      }
    this.tradeTime = tradeTime;
    return this;
  }

  //get和set的时候. set不单纯就就是直接set 我们在这里做一些简单的处理
  //我们还是要明明白白的将dao的职责写到dao层  对于实体的充血 一般也是建议做一些简单的逻辑校验
}
